<?php
namespace app\api\controller\store;

use app\common\controller\Api;
use app\common\controller\services\User as UserServices;
use app\common\controller\GpsUtils;
use think\Db;

class Store extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];


    /**
     * 中心/空间信息
     * @path api/store/store/index
     */
    public function index()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $store = db('store')->field('store_name,avatar,kefu_qrcode,business_start_time,business_end_time,province,city,area,address,lat,lng')->where('id',$storeId)->find();
        $store = addWebSiteUrl($store,['avatar','kefu_qrcode']);
        $province = db('area')->where('id',$store['province'])->value('name');
        $city = db('area')->where('id',$store['city'])->value('name');
        $area = db('area')->where('id',$store['area'])->value('name');
        $store['province_name'] = $province;
        $store['city_name'] = $city;
        $store['area_name'] = $area;
        $backList = [
            '$store'=>$store
        ];
        $this->success('请求成功',$backList);
    }

    /**
     * 中心/空间列表
     * @path api/store/store/storeList
     */
    public function storeList()
    {
        $keyWord = $this->request->param('key_word','');
        $page = $this->request->param('page',1);
        $lat = $this->request->param('lat','');
        $lng = $this->request->param('lng','');
        if (!empty($lat) && !empty($lng)) {
            //坐标转换
            
            $gpsUtils = new GpsUtils();
            $tengxunToBaidu = $gpsUtils->wgs84ToBd09($lat,$lng);
            $lat = $tengxunToBaidu[0];
            $lng = $tengxunToBaidu[1];
        }

        $userId = $this->auth->id;
        $timet = time();

        $where = "is_ban = '0'";
        $where.= " AND is_del = '0'";
        $where.= " AND xvstatus = '2'";
        $where.= " AND is_card_pay = '1'";//缴费的才能让用户绑定
        $where.= " AND end_time > '{$timet}'";
        if (!empty($keyWord)) {
            $where.= " AND store_name like '%".$keyWord."%'";
        }
        $order = "distance asc";
        $limit = 10;
        $start = ($page - 1) * $limit;

        $user = db('user')->where('id',$userId)->find();
        if (!empty($user['store_id'])) {
            if (!empty($lng) && !empty($lat)) {
                //进入这个判断是因为根据经纬度获取距离展示到页面
                

                $where = "is_ban = '0'";
                $where.= " AND is_del = '0' AND id = ".$user['store_id'];
                $sql = "SELECT id,store_name,tel,address,lat,lng,province,city,area,ROUND((2 * 6378.137 * ASIN(SQRT(POW(SIN(PI() * (" . $lat . " - lat) / 360), 2) + COS(PI() * " . $lat . " / 180) * COS(lat * PI() / 180) * POW(SIN(PI() * (" . $lng . " - lng) / 360), 2)))), 2) AS distance";
                $sql .=" from jianji_store  where ".$where." order by ".$order." limit ".$start.",".$limit;
                $store=Db::query($sql);
                $store = $store[0];
            } else {
                $store = db('store')->field("id,store_name,tel,province,city,area,address,'-' as distance")->where('id',$user['store_id'])->find();
            }
            $province = db('area')->where('id',$store['province'])->value('name');
            $city = db('area')->where('id',$store['city'])->value('name');
            $area = db('area')->where('id',$store['area'])->value('name');
            $store['province_name'] = $province;
            $store['city_name'] = $city;
            $store['area_name'] = $area;
            $this->success('请求成功',$store);
        }


        //经纬度存在
        if (!empty($lng) && !empty($lat)) {
            
            $sql = "SELECT id,store_name,tel,address,lat,lng,province,city,area,ROUND((2 * 6378.137 * ASIN(SQRT(POW(SIN(PI() * (" . $lat . " - lat) / 360), 2) + COS(PI() * " . $lat . " / 180) * COS(lat * PI() / 180) * POW(SIN(PI() * (" . $lng . " - lng) / 360), 2)))), 2) AS distance";
            $sql .=" from jianji_store  where ".$where." order by ".$order." limit ".$start.",".$limit;
        } else {
            $sql = "SELECT id,store_name,tel,address,lat,lng,province,city,area,'-' as distance";
            $sql .=" from jianji_store  where ".$where." order by add_time DESC limit ".$start.",".$limit;
        }
        $count_sql = "select count(*) as count";
        $count_sql .=" from jianji_store  where ".$where;
        $count=Db::query($count_sql);
        $count=$count[0]['count'];
        $list=Db::query($sql);
        $limit = 10;
        $total = ceil($count / $limit);
        foreach ($list as &$value){
//            if($value['distance'] > 0){
//                $value['distance'] = $value['distance']*1000;//bcdiv($value['distance'],1000,2);
//            }
            $province = db('area')->where('id',$value['province'])->value('name');
            $city = db('area')->where('id',$value['city'])->value('name');
            $area = db('area')->where('id',$value['area'])->value('name');
            $value['province_name'] = $province;
            $value['city_name'] = $city;
            $value['area_name'] = $area;
        }
        $data = [
            'total'=>$total,
            'list'=>$list
        ];
        $this->success('请求成功',$data);
    }


    /**
     * 用户绑定空间
     * @path api/store/store/storeBind
     */
    public function storeBind()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->request->param('store_id',0);
        $store = db('store')->where(['id'=>$storeId])->where('xvstatus',2)->find();
        
        if (empty($store)) {
            $this->error('空间不存在');
        }
        if ($store['is_ban'] == 1 || $store['is_del'] == 1 || $store['end_time'] < time()) {
            $this->error('空间状态异常');
        }

        db('user')->where('id',$userId)->update([
            'store_id'=>$storeId,
            'edittime'=>time()
        ]);
        $this->success('绑定空间成功');
    }

    /**
     * 取消绑定
     * @path api/store/store/storeUnBind
     */
    public function storeUnBind()
    {
        $userId = $this->auth->id;
        $storeId = $this->auth->store_id;
        if (empty($storeId)) {
            $this->error('非法请求');
        }
        $userServices = new UserServices();
        Db::startTrans();
        $result = $userServices->unBindStore($userId);
        if ($result['code'] == 201) {
            Db::rollback();
            $this->error($result['msg']);
        }
        Db::commit();
        $this->success('已解除绑定');
    }
}
